package com.cc.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cc.mall.config.HttpClient;
import com.cc.mall.entity.OfflineOrderEntity;
import com.cc.mall.feign.UserFeign;
import com.cc.mall.service.OfflineOrderService;
import com.cc.mall.vo.OrderDetail;
import com.cc.user.entity.UserEntity;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cc.mall.dao.OnlineOrderDao;
import com.cc.mall.entity.OnlineOrderEntity;
import com.cc.mall.service.OnlineOrderService;
import org.springframework.util.StringUtils;


@Service("onlineOrderService")
public class OnlineOrderServiceImpl extends ServiceImpl<OnlineOrderDao, OnlineOrderEntity> implements OnlineOrderService {

    @Autowired
    private OfflineOrderService offlineOrderService;

    @Autowired
    private UserFeign userFeign;

    @Override
    public List<OfflineOrderEntity> getOrderList(Map<String,Object> params) {
        String mobile = (String) params.get("mobile");
        String nickname = (String) params.get("nickname");
        QueryWrapper<OfflineOrderEntity> queryWrapper2 = new QueryWrapper<>();
        QueryWrapper<OnlineOrderEntity> queryWrapper1 = new QueryWrapper<>();
        if(!(StringUtils.isEmpty(mobile) && StringUtils.isEmpty(nickname))){
            UserEntity user = userFeign.getUserByMobileOrNickname(mobile, nickname);
            if(user != null){
                queryWrapper1.eq("uid",user.getUid());
                if(user.getPermission() == 1){
                    // 员工
                    queryWrapper2.eq("eid",user.getUid());
                }else {
                    // 客户
                    queryWrapper2.eq("cid",user.getUid());
                }
            }else {
                return new ArrayList<OfflineOrderEntity>();
            }

        }
        List<OfflineOrderEntity> offlineOrderEntities = offlineOrderService.list(queryWrapper2);
        List<OnlineOrderEntity> onlineOrderEntities = baseMapper.selectList(queryWrapper1);
        for (OnlineOrderEntity onlineOrderEntity : onlineOrderEntities) {
            OfflineOrderEntity offlineOrderEntity = new OfflineOrderEntity();
            BeanUtils.copyProperties(onlineOrderEntity,offlineOrderEntity);
            // 剩下字段不匹配的，进行手动赋值
            // todo offlineOrderEntity.setCid();
            offlineOrderEntity.setOfflineOrderStatus(onlineOrderEntity.getOnlineOrderStatus());
            offlineOrderEntities.add(offlineOrderEntity);
        }
        return offlineOrderEntities;
    }

    @Override
    public List<OrderDetail> getOnlineOrderDetailByOrderId(Long orderId) {
        return baseMapper.getOnlineOrderDetailByOrderId(orderId);
    }

    @Override
    public Map payOrderWx(Long orderId) {
        try {
            OnlineOrderEntity order = baseMapper.selectById(orderId);
            Map<String,String> m=new HashMap();
            // 24小时订单
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.HOUR, 24);// 24小时制
            date = cal.getTime();
            String time_expire = sdf.format(date);
            //1、设置支付参数
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");// 商户号
            m.put("nonce_str", WXPayUtil.generateNonceStr());// 随机字符串
            m.put("body", "宣酒");
            m.put("out_trade_no", orderId.toString());
            m.put("total_fee", order.getAmountsPayable().multiply(new BigDecimal("100")).longValue()+"");// 单位分
            m.put("time_expire",time_expire);// 超时时间
            m.put("spbill_create_ip", "127.0.0.1");// 终端ip
            m.put("notify_url", "http://124.70.217.108/:88/api/mall/notifyUrl2");// 异步通知
            m.put("trade_type", "APP");// 交易类型
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));// 私钥
            client.setHttps(true);
            client.post();
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            System.out.println(resultMap);
            Map map = new HashMap();
            map.put("out_trade_no", orderId.toString());
            map.put("total_fee", order.getAmountsPayable());
            map.put("result_code", resultMap.get("result_code"));
            map.put("code_url", resultMap.get("code_url"));
            map.put("prepay_id",resultMap.get("prepay_id"));
            return map;
        }catch (Exception e){
            throw new RuntimeException("微信二维码");
        }
    }

    @Override
    public Page<OnlineOrderEntity> getOnlineOrderList(Map<String, Object> params) {
        String orderId = (String)  params.get("orderId");
        Long page = Long.parseLong((String) params.get("page"));
        Long limit = Long.parseLong((String) params.get("limit"));
        Page<OnlineOrderEntity> onlineOrderEntityPage = new Page<>(page,limit);
        String mobile = (String) params.get("mobile");
        String nickname = (String) params.get("nickname");
        QueryWrapper<OnlineOrderEntity> queryWrapper = new QueryWrapper<>();
        if(!(StringUtils.isEmpty(mobile) && StringUtils.isEmpty(nickname))) {
            UserEntity user = userFeign.getUserByMobileOrNickname(mobile, nickname);
            if(user != null){
                if(user.getPermission() == 1){
                    // 员工
                    return onlineOrderEntityPage;
                }else {
                    // 客户
                    queryWrapper.eq("uid",user.getUid());
                }
            }else {
                return onlineOrderEntityPage;
            }
        }
        if(!StringUtils.isEmpty(orderId)){
            int length = orderId.split("").length;
            if(length <=19){
                queryWrapper.eq("id",Long.parseLong(orderId));
            }else {
                return onlineOrderEntityPage;
            }
        }
        baseMapper.selectMapsPage(onlineOrderEntityPage,queryWrapper);
        return onlineOrderEntityPage;
    }
}